//
//  CXStatusDAL.swift
//  Project03-Weibo-swift
//
//  Created by w on 16/2/2.
//  Copyright © 2016年 w. All rights reserved.
//

import UIKit
/**
 1. 负责数据的离线缓存。
 2. 负责数据的在线下载（包括上拉和下拉刷新操作）
*/

private let cacheDeadline:Double = 3600 * 24 * 7
class CXStatusDAL: NSObject {

    //一个类方法来读取本地数据，如果本地读取失败，则在线下载
    class func loadData(sinceId sinceId: Int64, maxId: Int64, complete: ((result: [[String: AnyObject]]?) -> Void)) {
        
        //从本地读取数据
        if let cacheData = getCacheData(sinceId: sinceId, maxId: maxId) where cacheData.count > 0 {
            print("本地有数据")
            complete(result: cacheData)
            return
        }
        
        //从网络加载数据
        CXNetworkTool.sharedTool.loadHomeStatuses(CXUserInfoViewModel.sharedUserModel.accessToken!, sinceId: sinceId, maxId: maxId) { (response, error) -> Void in
            //从网络加载失败
            if error != nil {
                print("加载失败\(error)")
                complete(result: nil)
                return
            }
            //确保下载的数据满足规定格式
            guard let responseDict = response?["statuses"] as? [[String : AnyObject]] else {
                print("下载的数据不符合规定格式")
                complete(result: nil)
                return
            }
            
            //缓存数据
            cacheData(responseDict)
            //返回数据
            complete(result: responseDict)
        }
    }
    //MARK: 清除缓存
    class func clearCache() {
        print("清除缓存")
        
        /**
         仿 SDWebImage 清除7天之前的数据
        */
        DateFormator.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = DateFormator.stringFromDate(NSDate(timeIntervalSinceNow: -cacheDeadline))
        
        let sql = "DELETE FROM T_Status WHERE createtime < \(dateStr)"
        
        SQLiteManager.sharedManager.dbQueue.inDatabase { (db) -> Void in
            
            if !db.executeUpdate(sql, withArgumentsInArray: nil) {
                print("删除缓存失败")
            } else {
                print("删除缓存成功")
            }
        }
    }
    //MARK: 缓存数据到本地
    class func cacheData(statuses: [[String: AnyObject]]) {
        // userid
        guard let userid = CXUserInfoViewModel.sharedUserModel.userInfo?.uid else {
            print("缓存用户数据 -- id 为空")
            return
        }
        //如果不加入replace操作 则会造成重复插入数据的现象 导致程序出错
        let sql = "INSERT OR REPLACE INTO T_Status (statusid, status, userid) VALUES (?, ?, ?)"
        
        //执行; 批量插入操作 采用事务来处理
        SQLiteManager.sharedManager.dbQueue.inTransaction { (db, rollback) -> Void in
            
            for dict in statuses {
                
                let statusId = dict["id"]
                //将数据序列化再缓存,模仿数据传输过程，并节约存储空间
                let status = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
                //如果插入数据失败
                if !db.executeUpdate(sql, withArgumentsInArray: [statusId!, status, userid]) {
                    print("缓存数据失败")
                    rollback.memory = true //回滚
                    break
                }
            }
        }
    }
    //MARK: 从本地获取数据
    class func getCacheData(sinceId sinceId: Int64, maxId: Int64) -> [[String: AnyObject]]? {
        
        print("从本地读取数据开始 需要sinceId: \(sinceId) maxId: \(maxId)")
        
        //如果userid为空 则返回nil
        guard let userId = CXUserInfoViewModel.sharedUserModel.userInfo?.uid else {
            print("user ID 为空")
            return nil
        }
        /**
         
         "statusid" INTEGER NOT NULL,
         "status" TEXT,
         "userid" INTEGER,
         "createtime" TEXT DEFAULT (datetime('now','localtime')),
         
         SELECT statusid, status, userid FROM T_Status
         WHERE userid = '5568397832'
         -- AND statusid < 3936746674813000
         AND statusid > 3936748814364130
         ORDER BY statusid DESC
         LIMIT 20

         */
        var sql = "SELECT statusid, status, userid FROM T_Status WHERE userid = \(userId) \n"
        
        if sinceId > 0 {
            sql += "AND statusid > \(sinceId) \n"
        } else if maxId > 0 {
            sql += "AND statusid < \(maxId+1) \n"
        }
        sql += "ORDER BY statusid DESC \n"
        sql += "LIMIT 20"
        
        let resDict = SQLiteManager.sharedManager.execOperation(sql)
        
        var res = [[String: AnyObject]]()
        
        for dict in resDict {
            
            //将二进制数据反序列化
            let statusDict = try! NSJSONSerialization.JSONObjectWithData(dict["status"] as! NSData, options: []) as! [String: AnyObject]
            //加入结果集
            res.append(statusDict)
        }
        return res
    }
}
